package com.cn.chaomeng.controller;

import com.cn.chaomeng.constant.SysParam;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author 范中燊
 * @version V1.0
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: TODO
 * @date ${date} ${time}
 */
@Controller
@RequestMapping("file")
public class FileController
{
    private final Logger logger = Logger.getLogger(FileController.class);

    /**
     * 获取图片
     *
     * @throws
     */
    @RequestMapping("/getPic")
    @ResponseBody
    public void getpic(HttpServletRequest request, HttpServletResponse response)
        throws Exception
    {
        String rootPath = SysParam.UPLOAD_ADDR;
        String path = request.getParameter("filePath");
        File file = new File(rootPath + path);
        String filename = file.getName();
        InputStream fis = new BufferedInputStream(new FileInputStream(rootPath + path));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }
}
